package m4;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();//连接
        Channel c = con.createChannel();//通信通道
        //1.随机队列  2.交换记   3.绑定，设置绑定键
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue, false, true, true, null);
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        System.out.println("输入绑定关键词，用空格隔开：");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");//\s是空白字符，+是1到多个
        for (String k : a) {
            c.queueBind(queue, "direct_logs", k);
        }

        //从队列正常的消费数据
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到："+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //从自己的队列正常接收消息
        c.basicConsume(queue,true,deliverCallback,cancelCallback);

    }
}
